package com.supermate.init.util;


import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

public class LogUtil {

    private final static Logger log = LoggerFactory.getLogger(LogUtil.class);

    public static void info(String businessInfo, Object[] inputParams, Object outputParam) {
        log.info(
                formatLogInfo(businessInfo, convertObject2Str(inputParams), convertObject2Str(outputParam))
        );
    }

    public static void error(String businessInfo, Object[] inputParams, Object outputParam) {
        log.error(
                formatLogInfo(businessInfo, convertObject2Str(inputParams), convertObject2Str(outputParam))
        );
    }

    public static void warn(String businessInfo, Object[] inputParams, Object outputParam) {
        log.warn(
                formatLogInfo(businessInfo, convertObject2Str(inputParams), convertObject2Str(outputParam))
        );
    }

    private static String convertObject2Str(Object object) {
        try {
            if (Objects.isNull(object)) {
                return null;
            }
            if (object instanceof String) {
                return (String)object;
            } else if (object instanceof Throwable) {
                return ExceptionUtils.getStackTrace((Throwable) object);
            } else {
                return JSON.toJSONString(object);
            }
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
            return null;
        }
    }

    private static String[] convertObject2Str(Object[] objects) {
        if (Objects.isNull(objects)) {
            return null;
        }
        String[] objectStrs = new String[objects.length];
        for (int i = 0; i < objects.length; i++) {
            objectStrs[i] = convertObject2Str(objects[i]);
        }
        return objectStrs;
    }

    private static String formatLogInfo(String businessInfo, String[] inputParams, String outputParam) {
        String inputs = inputParams == null ? null : String.join(",", inputParams);
        return  "[businessInfo:" + businessInfo + "]" +
                "[inputParams:" + inputs + "]" +
                "[outputParams:" + outputParam + "]";
    }

}
